from HTMLTestRunner import HTMLTestRunner
from email.mime.text import MIMEText
from email.header import Header
import os
import smtplib
import unittest
import time

#定义发送邮件
def send_email(file_new):
    fp = open(file_new,"rb")
    mail_body = fp.read()
    fp.close()
    msg = MIMEText(mail_body,"html","utf-8")
    msg['Subject']=Header("自动化测试报告","utf-8")

    smtp = smtplib.SMTP()
    smtp.connect("smtp.163.com")
    smtp.login("15216707828@163.com","15216707828ll")
    smtp.sendmail("15216707828@163.com","1926634636@qq.com",msg.as_string())
    smtp.quit()
    print("email has send out!")

#查找测试用例，找到最新生成的测试报告
def new_report(testreport):
    lists = os.listdir(testreport)
    lists.sort(key =lambda fn: os.path.getmtime(testreport+'\\'+fn))
    file_new = os.path.join(testreport,lists[-1])
    print(file_new)
    return file_new
if __name__ == '__main__':
    now = time.strftime("%Y-%m-%d %H-%M-%S")
    filename= './jingdong/report/'+now+'result.html'
    fp= open(filename,"wb")
    runner = HTMLTestRunner(stream=fp,title="京东社区登录功能自动化测试报告",description="环境：windows10 浏览器：chrome")
    discover= unittest.defaultTestLoader.discover(start_dir='./jingdong/testcase',pattern="*sta.py")
    runner.run(discover)
    fp.close()
    file_path = new_report('./jingdong/report/')
    send_email(file_path)